<?php
require_once(dirname(__FILE__) . "/../../config.php");
ini_set('date.timezone', 'Asia/Shanghai');
error_reporting(E_ERROR);
require_once "../lib/WxPay.Api.php";
require_once "WxPay.JsApiPay.php";
require_once 'log.php';
session_start();
$ddh = $_SESSION['ddh'];
if (substr($ddh, 0, 3) == 'KE-')
{
    $arr          = $dsql->GetOne("select * from #@__shops_orders where oid = '" . $ddh . "'");
    $trr          = $dsql->GetOne("select * from #@__arctype where  id = '" . $arr['pid'] . "'");
    $arr['pname'] = $trr['typename'];
    if (!is_array($arr))
    {
        die("课程订单号" . $_GET['ddh'] . "有误，请重新操作！");
    }
    $Goods_tag = '购买课程';
    $jiage     = $arr['money'] = $arr['price'];
}
else
{
    $arr = $dsql->GetOne("select * from #@__member_operation where buyid = '" . $ddh . "'");
    if (!is_array($arr))
    {
        die("订单号" . $_GET['ddh'] . "有误，请重新操作！");
    }
    $Goods_tag = '会员充值';
    $jiage     = $arr['money'];
}
$mid = $cfg_ml->M_ID;
//初始化日志
$logHandler = new CLogFileHandler("../logs/" . date('Y-m-d') . '.log');
$log        = Log::Init($logHandler, 15);
//打印输出数组信息
function printf_info($data)
{
    foreach ($data as $key => $value)
    {
        echo "<font color='#00ff55;'>$key</font> : $value <br/>";
    }
}

//①、获取用户openid
$tools  = new JsApiPay();
$openId = $tools->GetOpenid();
//②、统一下单
$input = new WxPayUnifiedOrder();
$input->SetBody($arr['pname']);
$input->SetAttach($arr['pname']);
$input->SetOut_trade_no($ddh);
$jiage = $jiage * 100;
$input->SetTotal_fee($jiage);
$input->SetTime_start(date("YmdHis"));
$input->SetTime_expire(date("YmdHis", time() + 600));
$input->SetGoods_tag("" . $cfg_webname);
$input->SetNotify_url($mcfg_basehost . "/user/weixinpay/example/notify.php");
$input->SetTrade_type("JSAPI");
$input->SetOpenid($openId);
$order           = WxPayApi::unifiedOrder($input);
$jsApiParameters = $tools->GetJsApiParameters($order);
$editAddress     = $tools->GetEditAddressParameters();
?>
<html>
<head>
    <meta charset="utf-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"/>
    <title><?php echo $cfg_webname; ?>支付中心</title>
    <script type="text/javascript">
        //供使用者调用  
        function trim(s) {
            return trimRight(trimLeft(s));
        }

        //去掉左边的空白  
        function trimLeft(s) {
            if (s == null) {
                return "";
            }
            var whitespace = new String(" \t\n\r");
            var str = new String(s);
            if (whitespace.indexOf(str.charAt(0)) != -1) {
                var j = 0, i = str.length;
                while (j < i && whitespace.indexOf(str.charAt(j)) != -1) {
                    j++;
                }
                str = str.substring(j, i);
            }
            return str;
        }

        //去掉右边的空白   
        function trimRight(s) {
            if (s == null) return "";
            var whitespace = new String(" \t\n\r");
            var str = new String(s);
            if (whitespace.indexOf(str.charAt(str.length - 1)) != -1) {
                var i = str.length - 1;
                while (i >= 0 && whitespace.indexOf(str.charAt(i)) != -1) {
                    i--;
                }
                str = str.substring(0, i + 1);
            }
            return str;
        }

        //调用微信JS api 支付
        function jsApiCall() {
            WeixinJSBridge.invoke(
                'getBrandWCPayRequest',
                <?php echo $jsApiParameters; ?>,
                function (res) {
                    WeixinJSBridge.log(res.err_msg);
                    var Cts = trim(res.err_msg);
                    if (Cts.indexOf(":ok") > 0) {
                        window.location.href = '/user/';
                    } else {
                        alert('支付失败');
                    }
                }
            );
        }

        function callpay() {
            if (typeof WeixinJSBridge == "undefined") {
                if (document.addEventListener) {
                    document.addEventListener('WeixinJSBridgeReady', jsApiCall, false);
                } else if (document.attachEvent) {
                    document.attachEvent('WeixinJSBridgeReady', jsApiCall);
                    document.attachEvent('onWeixinJSBridgeReady', jsApiCall);
                }
            } else {
                jsApiCall();
            }
        }
    </script>
    <script type="text/javascript">
        //获取共享地址
        function editAddress() {
            WeixinJSBridge.invoke(
                'editAddress',
                <?php echo $editAddress; ?>,
                function (res) {
                    var value1 = res.proviceFirstStageName;
                    var value2 = res.addressCitySecondStageName;
                    var value3 = res.addressCountiesThirdStageName;
                    var value4 = res.addressDetailInfo;
                    var tel = res.telNumber;

                    alert(value1 + '|' + value2 + '|' + value3 + '|' + value4 + '|' + ":" + tel);
                }
            );
        }

        window.onload = function () {
        };
    </script>
    <style type="text/css">
        body {
            background:#fff;
            font-size:14px;
            color:#333;
            font-family:-apple-system, BlinkMacSystemFont, Helvetica Neue, PingFang SC, Microsoft YaHei, Source Han Sans SC, Noto Sans CJK SC, WenQuanYi Micro Hei, sans-serif;
        }

        * {
            margin:0;
            padding:0;
        }

        ul, li {
            list-style:none;
        }

        h1, h2, h3, h4, h5, h6 {
            font-size:100%;
            font-weight:normal;
        }

        i, em {
            font-style:normal;
        }

        a {
            text-decoration:none;
            color:#333;
        }

        a:hover {
            text-decoration:none;
            color:#23b8ff;
        }

        button {
            vertical-align:middle;
            list-style:none;
            outline:none;
            border:0;
            -webkit-tap-highlight-color:rgba(0, 0, 0, 0);
            -webkit-appearance:none;
        }

        .des-m {
            line-height:20px;
            font-size:14px;
            color:#999;
            padding:18px;
            border-bottom:1px solid #f5f5f5;
            background-color:#fff;
        }

        .wrapper {
            max-width:640px;
            min-width:320px;
            margin:0 auto;
        }

        /*在线支付*/
        .gd_bottom {
            width:100%;
            bottom:0;
            position:fixed;
            left:0;
        }

        .gdb_buybtn_pay {
            width:100%;
            line-height:60px;
            background:#ff700a;
            color:#fff;
            font-size:18px;
            padding:0;
            border-radius:0;
        }
    </style>
</head>
<body>
<div class="wrapper">

    <div class="dwz-fkz" style="font-size:16px;color:#333;text-align:center;padding-top:50px;">正在付款中，请稍等...</div>

    <div class="gd_info" style="display:none;">
        <p class="des-m">订单编号：<?php echo $ddh; ?></p>
        <p class="des-m">商品名称：<?php echo $arr['pname']; ?></p>
        <p class="des-m">商品价格：<span style="color:#f30;">￥<?php echo $arr['money']; ?></span></p>
    </div>

    <!-- 立即付款 -->
    <div class="gd_bottom" style="display:none;">
        <div class="gd_bottom_pay">
            <button type="submit" class="gdb_buybtn_pay" onClick="callpay()">立即付款</button>
        </div>
    </div>
    <!-- 立即付款 End -->

</div>

<script>callpay();</script>

</body>
</html>